//
//  LoginVerificationVC.swift
//  NewXueBa
//
//  Created by Shine on 2019/6/17.
//  Copyright © 2019 jmxQAQ. All rights reserved.
//

import UIKit

fileprivate let bcTimeCount: Int = 60

class LoginVerificationVC: UIViewController {

    @IBOutlet weak var descriLabel: UILabel!
    @IBOutlet weak var errorLabel: UILabel!
    @IBOutlet weak var verCodeView: UIView!
    @IBOutlet weak var sendButton: UIButton!
    
    var tfCodeView: HWTextCodeView?
    var inputPhone: String = ""
    fileprivate var timer: Timer?
    fileprivate var count: Int = bcTimeCount
    let vm = LoginVM()

    override func viewDidLoad() {
        super.viewDidLoad()
        setVerificationUI()
        sendTime()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        timer?.invalidate()
        timer = nil
    }
    
    @IBAction func backClick(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    func setVerificationUI() {
        
        self.fd_prefersNavigationBarHidden = true //隐藏导航栏
        descriLabel.text = "验证码已发送到 \(inputPhone)"
        tfCodeView = HWTextCodeView(count: 4, margin: 30)
        tfCodeView?.frame = CGRect(x: 0, y: 0, width: kScreenWidth-30, height: 75)
        tfCodeView?.delegate = self
        verCodeView.addSubview(tfCodeView!)
        tfCodeView?.becomeFirstResponder()
        sendButton.addTarget(self, action: #selector(request), for: .touchUpInside)
    }
    
    

}

extension LoginVerificationVC {
    // 重新获取按钮的点击事件
    @objc fileprivate func request() {
       
        let verifyStr = String(inputPhone.prefix(4))
        let verify_code = inputPhone + "#" + verifyStr + "#" + BC_Ver + "#" + BC_Ctype
        
        vm.getMsgMode(inputPhone, verify_code.md5.uppercased(), BC_Ver, BC_Ctype) { (bcCode) in
            self.manageCode(bcCode, false)
        }
    }
    // code的结果
    fileprivate func manageCode( _ bcCode: NSInteger, _ codeLogin: Bool) {
        switch bcCode {
        case 0:
            print("成功")
            if codeLogin {
                UIApplication.shared.delegate?.window??.rootViewController = BCBaseTabBarVC.rootTabbarClass()
                DispatchQueue.global().async {
                    //耗时操作
                WebSocketManager.sharedInstance().loginWebSocketBaseUrl(XueBa_WebSocketURL, port: XueBa_WebSocketPort, userUid: BCUserManager.shareManager.user_uid ?? "", userToken: BCUserManager.shareManager.user_token ?? "")
                }
            }
        case 40:
            print("发送验证码失败")
            self.showTipMsg("发送验证码失败", time: 1)
        case 41:
            print("手机号码处于黑名单中")
            self.showTipMsg("手机号码处于黑名单中", time: 1)
        case 42:
            print("超过今日短信发送数目")
            self.showTipMsg("超过今日短信发送数目", time: 1)
        case 43:
            print("验证码发送频繁，请稍后再试")
            self.errorLabel.isHidden = false
        case 44:
            self.showTipMsg("验证码输入错误", time: 1)
        case 45:
            self.showTipMsg("链接账号中心失败，稍后重试", time: 1)
        case 46:
            print("获取用户数据，状态错误")
        case 47:
            self.showTipMsg("自动注册失败", time: 1)
        default:
            break
        }
    }
    
    
   fileprivate func sendTime()  {
        self.count = bcTimeCount
        self.sendButton?.isEnabled = false
        self.sendButton?.setTitle("\(self.count)秒后重新获取", for: .normal)
        if timer == nil {
            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.countdown), userInfo: nil, repeats: true)
        }
        CFRunLoopAddTimer(CFRunLoopGetMain(), self.timer, CFRunLoopMode.defaultMode)
        
    }
    // 定时器执行的变化事件
    @objc fileprivate func countdown() {
        count -= 1
        if  count <= 0 {
            timer?.invalidate()
            sendButton?.setTitle("重新获取", for: .normal)
            sendButton?.isEnabled = true
            return
        } else {
            sendButton?.isEnabled = false
            sendButton?.setTitle("\(count)秒后重新获取", for: .normal)
        }
    }
}

extension LoginVerificationVC: HWTextCodeViewDelegate {
    
    func codeEditingChanged(_ textField: UITextField) {    }
    
    func codeEditingEnd(_ textField: UITextField) {
        if textField.text?.count == 4 {
            let verifyStr = String(inputPhone.prefix(4))
            let verify_code = inputPhone + "#" + verifyStr + "#" + BC_Ver + "#" + BC_Ctype
            vm.codeLogin(inputPhone, verify_code.md5.uppercased(), textField.text!, BC_Ver, BC_Ctype) { (bcCode) in
                self.manageCode(bcCode, true)
            }
        }
    }
    
}
